package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.GraphService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.CopyParentClassLoaderRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description: 结构说明：
 * field: 开始边::结束边
 * value: weight
 * redis command 查看：
 * 可以根据 hgetall graph::entire 命令查看已有的边。
 * NOTEME:我觉得可以存储相似文章：field-百分比；value-id1,id2;
 * NOTEME:如果用上 ZSet 的话，以一篇文章做一个 ZSet,key-其他文章的ID,score-百分比
 */
@Service
@Slf4j
public class SimpleGraphServiceImpl implements GraphService {

    /**
     * 一整张有向带权图
     */
    final String GRAPH_KEY = "graph::entire";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean addEdge(String start, String end, int weight) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        String key = generateKey(start, end);
        opsForHash.put(GRAPH_KEY, key, weight + "");
        log.info("key:{},weight:{}", key, weight);
        return true;
    }

    @Override
    public Integer getWeight(String start, String end) {
        String key = generateKey(start, end);
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        Object o = opsForHash.get(GRAPH_KEY, key);
        if (o == null) {
            return null;
        }
        int w = Integer.parseInt(o.toString());
        return w;
    }

    String generateKey(String start, String end) {
        return start + "::" + end;
    }
}
